"""
django_sqlite3_API.py
python使用django数据库, 实现增、删、查、改。供sockServer.py使用

>>> import django
>>> print(django.VERSION)
(1, 11, 5, 'final', 0)
winXP python3.4.3 测试通过
"""

import os
import sys
import django
# python使用django数据库，下面两条语句是必须的
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
#从项目中导出数据库
from account.models import UserInfo

def add(name, password, macaddrs):
	ret = False
	try:
		user = UserInfo(name=name, password=password, macaddrs=macaddrs)
		user.save()
		ret = True
	except Exception as ex:
		print("err: %s"%ex)
	return ret


def find_all():
	'''
	查找全部记录
	return: <QuerySet [<UserInfo: admin>, <UserInfo: wu>]> 
	'''
	return UserInfo.objects.all() 

def find_macaddrs(macaddrs):
	'''查找macaddrs记录'''
	return UserInfo.objects.filter(macaddrs=macaddrs)

def is_macaddrs(macaddrs):
	'''判断macaddrs记录是否存在'''
	ret = False
	if UserInfo.objects.filter(macaddrs=macaddrs):
		ret = True
	return ret

def is_name_pass(name, password):
    '''判断数据库中是否有name, pass记录'''
    ret = False
    if UserInfo.objects.filter(name=name, password=password):
    	ret = True
    return ret

def update_password_name(name, password):
    '''由name更新password记录'''
    ret = False
    if UserInfo.objects.filter(name=name).update(password=password):
    	ret = True
    return ret

def del_macaddrs(macaddrs):
    '''删除macaddrs记录...'''
    ret = False
    if UserInfo.objects.filter(macaddrs=macaddrs).delete():
    	ret = True
    return ret

def del_all():
    '''
    删除全部记录.
    '''
    ret = False
    if UserInfo.objects.all().delete():
    	ret = True
    return ret

def QuerySetToList(query):
	'''
	记录转换为Query列表
	query： <QuerySet [<User: admin>, <User: wu>]> 
	return: Query列表 <QuerySet [('admin', '123', '558899'), ('wu', '123', '668899')]>
	'''
	return query.values_list() 

if __name__ == '__main__':
	print(QuerySetToList(find_all())) #True

	'''
	add('admin', '123', '558899')
	add('wu', '123', '668899')
	query = find_all()
	print("Query列表：", QuerySetToList(query))

	print("所有记录：",find_all())
	print(is_macaddrs('668899'), find_all())  #True
	print(is_macaddrs('55668899'), find_all()) #False
	print(is_name_pass('admin', '123'), find_all()) #True
	print(update_password_name('wu', '888'), find_all()) #True
	print(update_password_name('wu123', '888'), find_all()) #False
	print(del_macaddrs('668899'), find_all(), QuerySetToList(find_all())) #True
	#print(del_all(), find_all())
	'''#https://blog.csdn.net/s_frozen/article/details/125291960